package com.app.studyroom;

import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.app.studyroom.view.PinCodeView;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;

import eightbitlab.com.blurview.BlurTarget;
import eightbitlab.com.blurview.BlurView;

public class AppLockActivity extends BaseActivity {

    private String savedPassword = "123456";
    private Handler timeHandler = new Handler();
    private Runnable timeRunnable;

    private Handler lockHandler = new Handler();
    private Runnable lockRunnable;

    private View passwordPanel;
    private BlurView blurView;
    private PinCodeView pinCodeView;
    private ImageView ivQRCode;

    private float touchDownY = 0f;
    private final float SWIPE_THRESHOLD = 100f;
    private boolean isAnimating = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.activity_app_lock);

        SharedPreferences prefs = getSharedPreferences("settings", MODE_PRIVATE);
        savedPassword = prefs.getString("lockScreenPassword", "123456");

        // 初始化视图
        TextView tvTime = findViewById(R.id.tvCurrentTime);
        TextView tvDate = findViewById(R.id.tvCurrentDate);
        TextView tvWeekday = findViewById(R.id.tvCurrentWeekday);
        TextView tvClassName = findViewById(R.id.tvCurrentClassName);
        tvClassName.setText(prefs.getString("currentClassName", "未设置教室"));

        passwordPanel = findViewById(R.id.password_panel);
        blurView = findViewById(R.id.blur_overlay);
        pinCodeView = findViewById(R.id.pinCodeView);
        ivQRCode = findViewById(R.id.ivQRCode);

        passwordPanel.setVisibility(View.GONE);
        blurView.setVisibility(View.GONE);

        // ✅ 初始化模糊效果
        View decorView = getWindow().getDecorView();
        BlurTarget backgroundInfo = findViewById(R.id.backgroundInfo); // 整个 FrameLayout
        Drawable windowBackground = decorView.getBackground();

        blurView.setupWith(backgroundInfo)
                .setFrameClearDrawable(windowBackground)
                .setBlurRadius(5f);

        // 点击模糊区域隐藏密码面板
        blurView.setOnClickListener(v -> {
            if (!isAnimating && passwordPanel.getVisibility() == View.VISIBLE) {
                isAnimating = true;
                blurView.animate().alpha(0f).setDuration(200).withEndAction(() -> blurView.setVisibility(View.GONE)).start();
                passwordPanel.animate().alpha(0f).setDuration(200).withEndAction(() -> {
                    passwordPanel.setVisibility(View.GONE);
                    isAnimating = false;
                }).start();
            }
        });
        updateTimeViews(tvTime, tvDate, tvWeekday);
        startTimeUpdater(tvTime, tvDate, tvWeekday);

        // 输入监听
        pinCodeView.setOnInputCompleteListener(code -> {
            resetLockTimer();
            if (code.equals(savedPassword)) {
                finish(); // 密码正确
            } else {
                Toast.makeText(this, "密码错误", Toast.LENGTH_SHORT).show();
                pinCodeView.clear();
            }
        });
        // 绑定数字按钮点击事件
        for (int i = 0; i <= 9; i++) {
            int id = getResources().getIdentifier("btn" + i, "id", getPackageName());
            int digit = i;
            findViewById(id).setOnClickListener(v -> pinCodeView.inputDigit(String.valueOf(digit)));
        }

        findViewById(R.id.btnDelete).setOnClickListener(v -> pinCodeView.deleteLast());
        findViewById(R.id.btnCancel).setOnClickListener(v -> {
            pinCodeView.clear();
            blurView.performClick(); // 关闭面板
        });
        lockRunnable = () -> {
            // 自动锁屏逻辑留空
        };
        resetLockTimer();

        try {
            String qrContent = "二维码内容";

            Map<EncodeHintType, Object> hints = new HashMap<>();
            hints.put(EncodeHintType.CHARACTER_SET, "UTF-8"); // 指定字符集
            hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H); // 容错级别

            QRCodeWriter writer = new QRCodeWriter();
            BitMatrix bitMatrix = writer.encode(qrContent, BarcodeFormat.QR_CODE, 400, 400, hints);

            int width = bitMatrix.getWidth();
            int height = bitMatrix.getHeight();
            Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);
            for (int x = 0; x < width; x++) {
                for (int y = 0; y < height; y++) {
                    bitmap.setPixel(x, y, bitMatrix.get(x, y) ? 0xFF000000 : 0xFFFFFFFF);
                }
            }

            ivQRCode.setImageBitmap(bitmap);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        resetLockTimer();

        switch (ev.getAction()) {
            case MotionEvent.ACTION_DOWN:
                touchDownY = ev.getY();
                break;
            case MotionEvent.ACTION_UP:
                float deltaY = touchDownY - ev.getY();
                if (deltaY > SWIPE_THRESHOLD && passwordPanel.getVisibility() != View.VISIBLE && !isAnimating) {
                    isAnimating = true;
                    blurView.setVisibility(View.VISIBLE);
                    blurView.setAlpha(0f);
                    blurView.animate().alpha(1f).setDuration(300).start();

                    passwordPanel.setVisibility(View.VISIBLE);
                    passwordPanel.setAlpha(0f);
                    passwordPanel.animate().alpha(1f).setDuration(300).withEndAction(() -> isAnimating = false).start();
                }
                break;
        }

        return super.dispatchTouchEvent(ev);
    }
    private void resetLockTimer() {
        cancelLockTimer();
        long timeout = getLockTimeout();
        if (timeout >= 0) {
            lockHandler.postDelayed(lockRunnable, timeout);
        }
    }
    private void cancelLockTimer() {
        lockHandler.removeCallbacks(lockRunnable);
    }
    private long getLockTimeout() {
        SharedPreferences prefs = getSharedPreferences("settings", MODE_PRIVATE);
        return prefs.getLong("sleepTimeoutMillis", 900_000L); // 默认15分钟
    }
    private void updateTimeViews(TextView tvTime, TextView tvDate, TextView tvWeekday) {
        Date now = new Date();
        String timeStr = new SimpleDateFormat("HH:mm", Locale.getDefault()).format(now);
        String dateStr = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault()).format(now);
        String weekdayStr = new SimpleDateFormat("EEEE", Locale.CHINA).format(now);
        tvTime.setText(timeStr);
        tvDate.setText(dateStr);
        tvWeekday.setText(weekdayStr);
    }
    private void startTimeUpdater(TextView tvTime, TextView tvDate, TextView tvWeekday) {
        timeRunnable = () -> {
            updateTimeViews(tvTime, tvDate, tvWeekday);
            timeHandler.postDelayed(timeRunnable, 60 * 1000);
        };
        timeHandler.post(timeRunnable);
    }
    @Override
    protected void onResume() {
        super.onResume();
        resetLockTimer();
    }
    @Override
    protected void onPause() {
        super.onPause();
        cancelLockTimer();
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (timeHandler != null && timeRunnable != null) {
            timeHandler.removeCallbacks(timeRunnable);
        }
        cancelLockTimer();
    }
    @Override
    public void onBackPressed() {
        // 禁用返回键
    }
}
